

package com.dog.basics.common.config;


import com.dog.basics.common.exception.CustomException;
import com.dog.basics.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlerResolver {


    @ExceptionHandler(value = {RuntimeException.class, IOException.class})
    @ResponseStatus(HttpStatus.OK)
    public R runtimeException(RuntimeException e) {
        e.printStackTrace();
        log.error("自定义异常,ex = {}", e.getMessage());
        return R.failed(e.getMessage());
    }

    /**
     * custom Exception
     * 自定义异常
     *
     * @param e
     * @return R
     */
    @ExceptionHandler(CustomException.class)
    @ResponseStatus(HttpStatus.OK)
    public R customException(CustomException e) {
        e.printStackTrace();
        log.error("自定义异常,ex = {}", e.getMessage());
        return R.failed(e.getCode(), e.getMessage());
    }

    /**
     * 全局异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public R handleGlobalException(Exception e) {
        e.printStackTrace();
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return R.failed(e.getLocalizedMessage());
    }

    /**
     * validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.OK)
    public R handleBodyValidException(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.error("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
        return R.failed(fieldErrors.get(0).getDefaultMessage());
    }


}
